/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.notice.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.modules.notice.annotation.MsgNotice;
import org.springblade.modules.notice.entity.BizMsgConfig;
import org.springblade.modules.notice.entity.BizMsgConfigRelation;
import org.springblade.modules.notice.enums.BusinessType;
import org.springblade.modules.notice.enums.TriggerNodeEnum;
import org.springblade.modules.notice.service.IBizMsgConfigRelationService;
import org.springblade.modules.notice.vo.BizMsgConfigChangStatusParam;
import org.springblade.modules.notice.vo.BizMsgConfigListParam;
import org.springblade.modules.notice.vo.BizMsgConfigVO;
import org.springblade.modules.notice.mapper.BizMsgConfigMapper;
import org.springblade.modules.notice.service.IBizMsgConfigService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务消息管理表 服务实现类
 *
 * @author ysq
 * @since 2024-11-20
 */
@Service
public class BizMsgConfigServiceImpl extends BaseServiceImpl<BizMsgConfigMapper, BizMsgConfig> implements IBizMsgConfigService {

	@Lazy
	@Autowired
	private IBizMsgConfigRelationService bizMsgConfigRelationService;

	@Override
	public IPage<BizMsgConfigVO> selectBizMsgConfigPage(IPage<BizMsgConfigVO> page, BizMsgConfigVO bizMsgConfig) {
		bizMsgConfig.setTenantId(AuthUtil.getTenantId());
		return page.setRecords(baseMapper.selectBizMsgConfigPage(page, bizMsgConfig));
	}

	@Override
	public boolean customUpdate(BizMsgConfig bizMsgConfig) {
		return this.updateById(bizMsgConfig);
	}

	@Override
	public List<BizMsgConfig> getBizMsgConfigList(BizMsgConfigListParam param) {
		return baseMapper.getBizMsgConfigList(param);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean customChangeStatus(List<BizMsgConfigChangStatusParam> params) {
		for (BizMsgConfigChangStatusParam param : params) {
			BizMsgConfig bizMsgConfig = getById(param.getId());
			if (bizMsgConfig == null) {
				continue;
			}
			if (param.getStatus() == bizMsgConfig.getStatus()) {
				continue;
			}

			/**
			 * 若修改的不是系统数据，则复制一份作为租户数据后再修改
			 */
			if (!AuthUtil.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) && bizMsgConfig.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) {
				BizMsgConfig tenantBizMsgConfig = getOne(Wrappers.<BizMsgConfig>lambdaQuery()
					.eq(BizMsgConfig::getBusinessType, bizMsgConfig.getBusinessType())
					.eq(BizMsgConfig::getNode, bizMsgConfig.getNode())
					.eq(BizMsgConfig::getTriggerCondition, bizMsgConfig.getTriggerCondition())
					.eq(BizMsgConfig::getTenantId, AuthUtil.getTenantId()));
				if (tenantBizMsgConfig != null) {
					tenantBizMsgConfig.setStatus(param.getStatus());
					this.updateById(tenantBizMsgConfig);
					continue;
				}

				// 复制一份，作为租户独立数据
				tenantBizMsgConfig = new BizMsgConfig();
				BeanUtils.copyProperties(bizMsgConfig, tenantBizMsgConfig, "id");
				tenantBizMsgConfig.setTenantId(AuthUtil.getTenantId());
				tenantBizMsgConfig.setStatus(param.getStatus());
				this.save(tenantBizMsgConfig);

				// 对应的通知模板关联关系也复制一份
				List<BizMsgConfigRelation> relationList = bizMsgConfigRelationService.list(Wrappers.<BizMsgConfigRelation>lambdaQuery()
					.eq(BizMsgConfigRelation::getBizMsgConfigId, param.getId())
					.eq(BizMsgConfigRelation::getTenantId, AuthUtil.getTenantId()));
				if (!relationList.isEmpty()) {
					for (BizMsgConfigRelation relation : relationList) {
						relation.setBizMsgConfigId(tenantBizMsgConfig.getId());
					}
					bizMsgConfigRelationService.updateBatchById(relationList);
				}
			} else {
				bizMsgConfig.setStatus(param.getStatus());
				this.updateById(bizMsgConfig);
			}
		}
		return true;
	}

	@Override
	@MsgNotice(businessType = BusinessType.REPAIR, node = TriggerNodeEnum.REMINDER, parameterSource = 1, parameterName = "id")
	public Map<String, Object> test(Long id) {
		Map<String, Object> map = new HashMap<>(2);
		map.put("id", id);
		return map;
	}


}
